<?php
namespace app\api\controller;

use app\api\job\GameNotifyJob;
use app\common\controller\WeiXinpay;
use think\Controller;
use think\facade\Log;
use app\common\model\Order;
use app\common\model\Gameplog;
use app\common\model\OrderLog;
use think\Db;
use think\facade\Request;
use think\Queue;

class Notify extends Controller
{
    // 支付宝回调
    public function alipay_notify()
    {
        try {
            // 获取通知参数
            $params = input('post.');

            // 记录通知日志
            Log::info('支付宝异步通知参数：' . json_encode($params));
            file_put_contents(__DIR__.'/alipay_notify.txt', json_encode($params) . "\n");
            
            // 验证签名
            $verifyResult = \app\common\controller\Alipay::verifyNotify($params);
            if (!$verifyResult) {
                Log::error('支付宝异步通知签名验证失败');
                return 'fail';
            }
            
            // 验证交易状态
            if ($params['trade_status'] != 'TRADE_SUCCESS') {
                Log::error('支付宝异步通知交易状态不正确：' . $params['trade_status']);
                return 'fail';
            }
            
            if ($this->orderHandle($params['out_trade_no'], $params['total_amount'], 1) === 'fail') {
                return 'fail';
            }
        
            // 返回成功
            return 'success';
            
        } catch (\Exception $e) {
            Log::error('支付宝异步通知处理异常：' . $e->getMessage());
            return 'fail';
        }
    }

    
    // 微信支付回调
    public function wechat_notify()
    {
        // 处理微信支付通知逻辑
        $body = file_get_contents('php://input');
                    // 记录通知日志
        Log::info('微信支付异步通知密文：' . $body);
        file_put_contents(__DIR__.'/weixin_notify.txt', $body . "\n");

        $params = WeiXinpay::verifyNotify($body, request()->header());

        Log::info('微信支付异步通知数据：' . json_encode($params));
        file_put_contents(__DIR__.'/weixin_notify.txt', json_encode($params) . "\n");

        // 验证交易状态
        if ($params['trade_state'] != 'SUCCESS') {
            Log::error('微信异步通知交易状态不正确：' . $params['trade_status']);
            return 'fail';
        }

        if ($this->orderHandle($params['out_trade_no'], $params['amount']['total']/100, 2) === 'fail') {
            return 'fail';
        }
        
        // 返回成功
        return 'success';
    }

    /**
     * 支付成功订单处理
     */
    private function orderHandle($trade_no, $total_amount, $type) {
        // 查询订单
        $order = Order::where([
            'order_no'=>$trade_no,
            'order_status'=>0, // 待支付
        ])->find();

        if (empty($order)) {
            Log::error('异步通知订单不存在：' . $trade_no);
            return 'fail';
        }
        // 验证订单金额 
        if ($order['amount'] != $total_amount) {
            Log::error("异步通知订单金额不匹配，订单号：{$trade_no}，订单金额：{$order['amount']}，通知金额: {$total_amount}");
            return 'fail';
        }
        Db::startTrans();
        try {
            // 更新订单状态
            $order->order_status = 1; // 支付成功
            $order->pay_time = date('Y-m-d H:i:s');
            $order->update_time = date('Y-m-d H:i:s');
            $order->save();

            // 记录游戏充值日志
            Gameplog::addLog([
                'uid' => $order['uid'],
                'cid' => $order['cid'],
                'gid' => $order['gid'],
                'sid' => $order['sid'],
                'order_no' => $order['order_no'],
                'order_status' => $order['order_status'],
                'amount' => $order['amount'],
                'type' => $type, // 支付宝支付
                'status' => 1, // 成功
                'create_time' => date('Y-m-d H:i:s'),
                'pay_time' =>$order['pay_time'],
                'pay_status' => 1
            ]);
            OrderLog::addLog($order->order_no, $order->order_status, $order->type);
            Db::commit();

            //添加redis队列、通知到游戏
            Queue::push(GameNotifyJob::class, ['order_no' => $trade_no]);
            
        } catch (\Exception  $e) {
            Log::error('订单处理异常：' . $e->getMessage());
            Db::rollback();
        }
    }
}
